<?php
	/**
	 * UPDATE DEAL EXPIRED DATE OR SOON TO DEACTIVE
	 */
    
    function compare_time_deactive()
    {
        $start = strtotime(get_option('last_update_deal_status'));
        $rs_seconds = time() - $start;
        $rs_hours = round($rs_seconds/60/60,1);
        if($rs_hours >= 24)
            return true;
        else
            return false;
    }
    function compare_time_active()
    {
        $last_active = get_option('last_active_deal_status');
        if($last_active != date('Y/m/d'))
            return true;
        else
            return false;
    }
    
    if(compare_time_deactive() == true)
    {
        deactive_expired_or_soon_deals();
    }
    if(compare_time_active() == true)
    {
        active_soon_deals();
    }
    
    // active soon deals
    function active_soon_deals()
    {
        global $wpdb;
		$d = date('y/m/d');
        $qr = "
        SELECT post_id FROM {$wpdb->postmeta} WHERE  
        meta_key = 'start_date_metadata' 
        AND CAST(meta_value AS DATE) = '$d'
        ";
        $rs = $wpdb->get_results($qr);
        
        $str_ids = '';
		if(count($rs) > 0)
        {
            foreach ($rs as $k => $v)
    		{
    			$str_ids .= $v->post_id;
    			if ($k != count($rs) - 1)
    				$str_ids .= ',';
    		}
            $qr2 = "UPDATE {$wpdb->postmeta} SET meta_value = 'active' WHERE meta_key = 'status_metadata' AND post_id IN ({$str_ids})";
			$rs2 = $wpdb->query($qr2);
        }
        update_option('last_active_deal_status',date('Y/m/d'));
    }
    // deactive expired and soon deals
	function deactive_expired_or_soon_deals()
	{
		global $wpdb;
		$d = date('y/m/d');
		$qr = "
        SELECT post_id FROM {$wpdb->postmeta} WHERE 
        (meta_key = 'end_date_metadata' AND CAST(meta_value AS DATE) < '$d')
        OR
        (meta_key = 'start_date_metadata' AND CAST(meta_value AS DATE) > '$d')
        ";
                
		$rs = $wpdb->get_results($qr);

		$str_ids = '';
		if(count($rs) > 0)
        {
            foreach ($rs as $k => $v)
    		{
    			$str_ids .= $v->post_id;
    			if ($k != count($rs) - 1)
    				$str_ids .= ',';
    		}
            $qr2 = "UPDATE {$wpdb->postmeta} SET meta_value = 'deactive' WHERE meta_key = 'status_metadata' AND post_id IN ({$str_ids})";
			$rs2 = $wpdb->query($qr2);
        }    
        update_option('last_update_deal_status',date('Y/m/d'));
	}

//	if (!wp_next_scheduled('cpx_update_deal_status'))
//	{
//		wp_schedule_event(time(), 'daily', 'cpx_update_deal_status');
//	}
//	add_action('cpx_update_deal_status', 'deactive_expired_or_soon_deals');
?>